package com.qf.electronic.mall.email.service.handler;

import com.qf.constant.RabbitConstant;
import com.qf.dto.EmailMessageDto;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

@Component
public class EmailHandler {

    @Autowired
    private JavaMailSender sender;

    @Autowired
    private TemplateEngine engine;
    @RabbitListener(queues = RabbitConstant.EMAIL_SEND_QUEUE)
    public void sendEmail(EmailMessageDto message){
        try{
            MimeMessage mimeMessage = sender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,true);
            //设置邮件标题
            helper.setSubject("请激活您的账号");
            //创建模板引擎
            Context context = new Context();
            //添加引用数据
            context.setVariable("username",message.getEmail().substring(0,message.getEmail().lastIndexOf("@")));
            context.setVariable("url",message.getUrl());
            //将模板与数据整合构成邮件内容
            String info = engine.process("emailtemplate", context);
            //发送html格式的邮件
            helper.setText(info,true);
            //邮件发送者
            helper.setFrom("goldendarkness111@126.com");
            helper.setTo(message.getEmail());
            //发送邮件
            sender.send(mimeMessage);
        }catch (MessagingException e){
            e.printStackTrace();
        }
    }
}
